<?php
/*------------------------------------------------------ */
//-- 提成处理
//-- Author: iqgmy
/*------------------------------------------------------ */

namespace distribution\base;

use app\BaseModel;
use app\distribution\model\DistributionJcLog;
use app\member\model\UsersLevelApplyModel;
use think\Db;
use app\AdminController;
use app\member\model\AccountModel;
use app\member\model\UsersBindSuperiorModel;
use app\member\model\{UsersModel, UsersLevelModel};
use app\shop\model\{OrderModel, OrderGoodsModel, GoodsModel};
use app\distribution\model\{DividendAwardModel, DividendRoleModel};
use think\facade\Cache;
use app\mainadmin\model\SmsTplModel;

class Dividend extends BaseModel
{
    public $UsersModel;

    public function __construct($Model)
    {
        parent::__construct();
        $this->UsersModel = new UsersModel();
        $this->Model = $Model;
    }

    /*------------------------------------------------------ */
    //-- 计算提成并记录或更新
    //-- $orderInfo array 订单数据
    //-- $type string 操作类型
    //-- $status int 分佣状态，操作类型为add时，根据传值设置默认状态
    //-- return bool 如果$type为add或订单为身份订单则返回数组
    /*------------------------------------------------------ */
    public function _eval(&$orderInfo, $type = '', $status = 0)
    {

        //身份订单处理
        if ($orderInfo['is_split'] > 0) return true;//需要拆单的不执行
        $upData = [];//更新分佣记录状态
        $OrderModel = new OrderModel();
        $order_operating = '';
        $send_msg = false;
        //先计算佣金

        //检测 如果购买代理升级商品的上级是会员 就将该用户移到会员上级代理

        //die;
        if ($type == 'add' || $type == 'change') {//写入分佣，普通订单下单时执行


//            $upData = $this->saveLog($orderInfo, $goodsList, $status); //佣金计算
//
//            // $res = $this->evalLevelUp($orderInfo);//升级处理
//            // // var_dump($res);
//            // print_r($upData);die;
//            if (is_array($upData) == false) return false;
//            if ($status == $OrderModel->config['DD_PAYED']) {
//                $res = $this->evalLevelUp($orderInfo);//升级处理
//                if ($res == false) return false;
//                if ($orderInfo['is_dividend'] == 0) {//第一次生成时才发送模板消息
//                    $this->Model->sendMsg('pay', $orderInfo['order_id']);//支付模板消息
//                }
//            }
//
//            return $upData;//返回数组
        }


        //
        if ($type == 'pay') {//订单支付成功
            if ($orderInfo['order_type'] == 4) {
                $user = $this->UsersModel->where('user_id', $orderInfo['user_id'])->find();
                if (!empty($user) && !empty($user['pid'])) {
                    $upUser = UsersModel::where(['user_id' => $user['pid']])->find();
                    if ($upUser['role_id'] == 3 || $upUser['role_id'] == 0) {
                        $pid = !empty($upUser['pid']) ? $upUser['pid'] : 0;
                        $dalili = false;
                        do {
                            if (empty($upUser['pid'])) {
                                break;
                            }
                            $upUser = UsersModel::where(['user_id' => $upUser['pid']])
                                ->field('role_id,user_id,pid')->find();
                            if (!empty($upUser) && $upUser['role_id'] == 1) {
                                $pid = 0;
                                $dalili = true;
                            }
                        } while ($pid > 0);
                        $user->pid = $dalili ? $upUser['user_id'] : 0;
                        $user->profit_pid = $dalili ? $upUser['user_id'] : 0;
                        $user->save();
                    }
                }
                //修改用户上级pid以及分佣ID
            }
            $isLook = redisLook('fr_shop_order_has_pay_' .  $orderInfo['order_id'],20);
            if($isLook ==true){
                $goodsList = (new OrderGoodsModel)->where('order_id', $orderInfo['order_id'])->select()->toArray();
                foreach ($goodsList as $k => $goods) {

                    //增加奖金池金额
                    $_goods = GoodsModel::where('goods_id', $goods['goods_id'])->field('shop_price,jc,award_value,send_bl,is_dividend,region_award_value')->find()->toArray();
                    if (!empty($_goods['jc'])) {
                        $_goods['jc'] = json_decode($_goods['jc'], true);
                        foreach ($_goods['jc'] as $key => $value) {
                            $jc = UsersLevelApplyModel::where('level_id', $key)->find();
                            $islog = DistributionJcLog::where(['jc_id' => $jc['level_id'], 'order_id' => $orderInfo['order_id'], 'goods_id' => $goods['goods_id']])->count();
                            if (!empty($jc) && !empty($value['scale']) && $islog == 0) {
                                $amount = bcmul($_goods['shop_price'] * $goods['goods_number'], (intval($value['scale']) / 100));
                                //dump($_goods['shop_price'] * $goods['goods_number']);
                                $data = [
                                    'jc_id' => $jc['level_id'],
                                    'goods_id' => $goods['goods_id'],
                                    'order_id' => $orderInfo['order_id'],
                                    'amount' => $_goods['shop_price'] * $goods['goods_number'],
                                    'enter_amount' => $amount,
                                    'createtime' => time(),
                                    'stage' => date('Ym'),
                                ];
                                $result = (new DistributionJcLog())->insert($data);
                                $jc->total_amount = $jc->total_amount + $amount;
                                $jcRes = $jc->save();
//                            if($result){
//                                $jc->total_amount = $jc->total_amount + $amount;
//                                $jcRes = $jc->save();
//                                if(!$jcRes){
//                                    return false;
//                                }
//                            }else{
//                                return false;
//                            }

                            }
                        }
                    }
                    //end
                    $goodsList[$k]['send_bl'] = $_goods['send_bl'];
                }

                $upData = $this->saveLog($orderInfo, $goodsList, $status); //佣金计算
                // $res = $this->evalLevelUp($orderInfo);//升级处理
                // // var_dump($res);
                // print_r($upData);die;
                if (is_array($upData) == false) return false;
                if ($status == $OrderModel->config['DD_PAYED']) {
                    $res = $this->evalLevelUp($orderInfo);//升级处理
                    if ($res == false) return false;
                    if ($orderInfo['is_dividend'] == 0) {//第一次生成时才发送模板消息
                        $this->Model->sendMsg('pay', $orderInfo['order_id']);//支付模板消息
                    }
                }

                $res = $this->evalLevelUp($orderInfo);//升级处理
                trace('升级处理返回' . $res, 'debug');
                //加盟区赠送复购积分 修改 linghan
                $sendMoney = $orderInfo['order_amount'] * ($goodsList[0]['send_bl'] / 100);
                if ($sendMoney > 0) {
                    $AccountModel = new AccountModel();
                    $inData['total_integral'] = $sendMoney;
                    $inData['use_integral'] = $inData['total_integral'];
                    if ($inData['total_integral'] > 0) {
                        $inData['change_type'] = 2;
                        $inData['by_id'] = $orderInfo['order_id'];
                        $inData['change_desc'] = '加盟区订单[' . $orderInfo['order_sn'] . ']赠送复购' . $sendMoney . '积分';
                        $AccountModel->change($inData, $orderInfo['user_id']);
                    }
                }
                if ($res == false) return false;
                $upData['status'] = $OrderModel->config['DD_PAYED'];
                $send_msg = true;
                $this->assemblyPay($orderInfo);


                return true;
            }
            return false;

        } elseif ($type == 'cancel') {//订单取消
            $upData['status'] = $OrderModel->config['DD_CANCELED'];
            $order_operating = '订单取消';
            $send_msg = true;
            $this->assemblyPay($orderInfo, 3);

        } elseif ($type == 'unpayed') {//未付款
            if ($orderInfo['order_status'] == $OrderModel->config['OS_CANCELED']) {
                $upData['status'] = $OrderModel->config['DD_CANCELED'];
            } elseif ($orderInfo['order_status'] == $OrderModel->config['OS_RETURNED']) {
                $upData['status'] = $OrderModel->config['DD_RETURNED'];
            } else {
                $upData['status'] = $OrderModel->config['DD_UNCONFIRMED'];
            }
            $this->assemblyPay($orderInfo, 2);
        } elseif ($type == 'shipping') {//发货
            $upData['status'] = $OrderModel->config['DD_SHIPPED'];
        } elseif ($type == 'unshipping') {//未发货
            $this->assemblyPay($orderInfo, 5);
            $upData['status'] = $OrderModel->config['DD_PAYED'];
        } elseif ($type == 'sign') {//签收
            $upData['status'] = $OrderModel->config['DD_SIGN'];
            $this->assemblySign($orderInfo);
        } elseif ($type == 'unsign') {//撤销签收
            $this->assemblyPay($orderInfo, 5);
            return $this->Model->returnArrival($orderInfo['order_id'], 'unsign', $orderInfo['user_id']);
        } elseif ($type == 'returned') {//退货
            return $this->Model->returnArrival($orderInfo['order_id'], 'returned', $orderInfo['user_id']);
        }

        if (empty($upData) == false) {//更新分佣状态
            $upWhere[] = ['order_id', '=', $orderInfo['order_id']];
            $upWhere[] = ['order_type', '=', 'order'];
            //如果已经返佣了。不能继续修改分佣状态 2020-9-10 11:36:03-xgh
            $upWhere[] = ['status', '<>', $OrderModel->config['DD_DIVVIDEND']];
            $count = $this->Model->where($upWhere)->count();
            if ($count < 1) return true;//如果没有佣金记录不执行
            $upData['update_time'] = time();
            $res = $this->Model->where($upWhere)->update($upData);
            if ($res < 1) return false;
        }

        if ($send_msg == true) {
            $this->Model->sendMsg($type, $orderInfo['order_id'], $order_operating);//发送模板消息
        }

        if ($type == 'sign' && $orderInfo['order_type'] == 0) {//签收,执行佣金到帐
            $shop_after_sale_limit = settings('shop_after_sale_limit');
            if ($shop_after_sale_limit == 0) {
                //return $this->Model->evalArrival($orderInfo['order_id'], 'order');
            }
        } elseif ($type == 'pay') {
            //return $this->Model->evalArrival($orderInfo['order_id'], 'order');

        }

        return true;
    }

    /**
     * [assemblySign  自定义交易组件同步订单签收]
     * @param array $orderInfo [订单信息]
     */
    public function assemblySign($orderInfo = [])
    {
        $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();
        $assemblyInfo = $WeixinVideoOrderModel->where('out_order_id', $orderInfo['order_id'])->find();
        if (empty($assemblyInfo) == false) {
            $assemblyInfo = $assemblyInfo->toArray();
            $param = [];
            $param['order_id'] = $assemblyInfo['order_id'];
            $param['out_order_id'] = $assemblyInfo['out_order_id'];
            $param['openid'] = $assemblyInfo['openid'];
            $res = $WeixinVideoOrderModel->signOrder($param);
        }
        return true;
    }

    /**
     * [assemblyPay 自定义交易组件同步订单状态]
     * @param array $orderInfo [订单信息]
     * @param integer $status [订单状态，1:支付成功,2:支付失败,3:用户取消,4:超时未支付;5:商家取消;10:其他原因取消]
     */
    public function assemblyPay($orderInfo = [], $status = 1)
    {
        $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();
        $assemblyInfo = $WeixinVideoOrderModel->where('out_order_id', $orderInfo['order_id'])->find();
        if (empty($assemblyInfo) == false) {
            $assemblyInfo = $assemblyInfo->toArray();
            $WeixinVideoOrderModel->updateOrderStatus($assemblyInfo, $status, $orderInfo['transaction_id']);
        }
        return true;
    }

    /**
     * [assemblyAddOrder 自定义交易组件提交订单]
     * @param array $orderInfo [订单信息]
     * @param array $goodsList [购买商品]
     */
    public function assemblyAddOrder($orderInfo = [], $goodsList = [])
    {
        $WeixinVideoGoodsModel = new \app\weixin\model\WeixinVideoGoodsModel();
        $product_infos = [];
        $i = 0;
        foreach ($goodsList as $goods) {
            $vgoods = $WeixinVideoGoodsModel->where('out_product_id', $goods['goods_id'])->find();
            if (empty($vgoods) == false) {
                $product_infos[$i]['out_product_id'] = $goods['goods_id'];
                $product_infos[$i]['out_sku_id'] = $goods['sku_id'];
                $product_infos[$i]['product_cnt'] = $goods['goods_number'];
                $product_infos[$i]['sale_price'] = $goods['sale_price'];
                $product_infos[$i]['path'] = "pages/shop/goods/info?goods_id=" . $goods['goods_id'];
                $product_infos[$i]['title'] = $goods['goods_name'];
                $product_infos[$i]['head_img'] = config('config.host_path') . $goods['goods_img'];
                $i++;
            }
        }
        if (empty($product_infos) == false) {
            $scene = input('scene');
            $times = date('Y-m-d H:i:s', time());
            $data = [];
            $data['create_time'] = $times;
            $data['type'] = 0;
            $data['out_order_id'] = $orderInfo['order_id'];
            $data['path'] = "pages/shop/order/info?order_id=" . $orderInfo['order_id'];


            $data['openid'] = (new \app\weixin\model\WeiXinUsersModel)->where('user_id', $orderInfo['user_id'])->value('wx_openid');
            $data['out_user_id'] = $orderInfo['user_id'];
            $data['scene'] = $scene;
            $data['order_detail'] = [];
            $data['order_detail']['product_infos'] = $product_infos;
            $data['order_detail']['pay_info']['pay_method'] = '微信支付';
            $data['order_detail']['pay_info']['prepay_id'] = 000000;
            $data['order_detail']['pay_info']['prepay_time'] = $times;
            $data['order_detail']['pay_info']['pay_method_type'] = 0;
            $data['order_detail']['price_info']['order_price'] = $orderInfo['order_amount'] * 100;
            $data['order_detail']['price_info']['freight'] = $orderInfo['shipping_fee'] * 100;
            $data['order_detail']['price_info']['discounted_price'] = ($orderInfo['diy_discount'] + $orderInfo['use_bonus'] + $orderInfo['discount']) * 100;
            $data['order_detail']['price_info']['additional_price'] = 0;
            $data['order_detail']['price_info']['additional_remarks'] = '';
            $data['delivery_detail']['delivery_type'] = 1;
            $data['address_info']['receiver_name'] = $orderInfo['consignee'];
            $data['address_info']['detailed_address'] = $orderInfo['address'];
            $data['address_info']['tel_number'] = $orderInfo['mobile'];

            $merger_name = explode(',', $orderInfo['merger_name']);
            $data['address_info']['country'] = $merger_name[0];
            $data['address_info']['province'] = $merger_name[1];
            $data['address_info']['city'] = $merger_name[2];
            $data['address_info']['town'] = '';

            $WeixinVideoOrderModel = new \app\weixin\model\WeixinVideoOrderModel();

            $res = $WeixinVideoOrderModel->addOrder($data);
            if ($res['errcode'] <= 0) {
                $data['package'] = json_encode($res['data'], JSON_UNESCAPED_UNICODE);
                $data['order_detail'] = json_encode($data['order_detail'], JSON_UNESCAPED_UNICODE);
                $data['delivery_detail'] = json_encode($data['delivery_detail'], JSON_UNESCAPED_UNICODE);
                $data['address_info'] = json_encode($data['address_info'], JSON_UNESCAPED_UNICODE);
                $data['order_id'] = $res['data']['order_id'];
                $data['ticket'] = $res['data']['ticket'];
                $data['ticket_expire_time'] = $res['data']['ticket_expire_time'];
                $data['final_price'] = $res['data']['final_price'];
                $data['add_time'] = time();
                $WeixinVideoOrderModel->save($data);
            }
        }
        return true;
    }

    /*------------------------------------------------------ */
    //-- 计算提成并记录或更新
    /*------------------------------------------------------ */
    public function saveLog(&$orderInfo, &$goodsList, $status = 0)
    {

        $returnArr['dividend_amount'] = 0;
        $nowLevel = 0;//当前处理级别
        $buyUserInfo = $this->UsersModel->info($orderInfo['user_id']);//获取购买会员信息
        //参与分佣商品处理
        $dividend_goods = [];//所有分佣商品
        $dividend_goods_total = 0;//所有分佣商品金额
        foreach ($goodsList as $k => $goods) {
            $_goods = GoodsModel::where('goods_id', $goods['goods_id'])->field('award_value,send_bl,is_dividend,region_award_value,goods_type,membermoney')->find()->toArray();

            $goodsList[$k]['send_bl'] = $_goods['send_bl'];
            if ($_goods['is_dividend'] == 1) {
                $diy_discount = 0;
                if ($orderInfo['diy_discount'] > 0) {//后台改价优惠
                    $total_price = $goods['sale_price'] * $goods['goods_number'];
                    $diy_discount = priceFormat($total_price / $orderInfo['goods_amount'] * $orderInfo['diy_discount']);
                }
                if ($goods['return_goods_number'] > 0) {//有退货处理
                    $goods['goods_number'] = $goods['goods_number'] - $goods['return_goods_number'];//购买数量减去已退货数量
                }
                $goods['goods_type'] = $_goods['goods_type'];
                $goods['membermoney'] = $_goods['membermoney'];
                $goods['award_value'] = json_decode($_goods['award_value'], true);
                $goods['region_award_value'] = json_decode($_goods['region_award_value'], true);
                $goods['goods_total'] = priceFormat($goods['sale_price'] * $goods['goods_number'] - $goods['usd_bonus_price'] - $diy_discount);//商品总价小计
                $dividend_goods_total += $goods['goods_total'];
                $dividend_goods[$goods['goods_id'] . '_' . $goods['sku_id']] = $goods;
            }
        } //参与分佣商品处理end
        //$parentId = $buyUserInfo['profit_pid'];//获取收益上级ID
        $parentId = $buyUserInfo['pid'];  //琳凯
        $UsersLevelModel = new \app\member\model\UsersLevelModel();
        $UsersLevelAgentModel = new \app\member\model\UsersLevelAgentModel();
        $levelList = $UsersLevelModel->getRows();
        // $diff_region = [];// 已分配出去的区域奖
        if ($orderInfo['order_type'] !== 5) {
            foreach ($levelList as $level) { // 区域奖
                $where = [];
                $where[] = ['province', '=', $orderInfo['province']];
                if ($level['identification'] == 'city_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                }
                if ($level['identification'] == 'district_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                    $where[] = ['district', '=', $orderInfo['district']];
                }
                if ($level['identification'] == 'street_agent') {
                    $where[] = ['city', '=', $orderInfo['city']];
                    $where[] = ['district', '=', $orderInfo['district']];
                    $where[] = ['street', '=', $orderInfo['street']];
                }

                $counter_file = 'Yhknew20230807-1.txt';
                $fopen = fopen($counter_file,'a+');
                fputs($fopen,date('Y-m-d H:i:s',time()).' orderInfo[street]:'.$orderInfo['street'].'，currentPhone：'.$orderInfo['street'].'\r\n');
                fclose($fopen);

                $where[] = ['level_id', '=', $level['level_id']];
                $agentInfo = $UsersLevelAgentModel->where($where)->find();
                unset($where);
                $dividend_amount_region = 0;
                if (empty($agentInfo) == false) {
                    foreach ($dividend_goods as $gk => $goods) {
                        $num = $goods['region_award_value'][$level['level_id']]['num'];  //奖励金额

                        if (empty($num) == false) {
                            //琳凯start 区域奖励级差奖励计算逻辑
                            $shengMoney = $goods['region_award_value'][3]['num'];   // 省奖励金额
                            $shiMoney = $goods['region_award_value'][2]['num'];   // 市奖励金额
                            $quMoney = $goods['region_award_value'][1]['num'];   // 区奖励金额
                            $jiedaoMoney = $goods['region_award_value'][4]['num'];   // 街道奖励金额

                            $wheresheng = [];
                            $wheresheng[] = ['province', '=', $orderInfo['province']];
                            $wheresheng[] = ['level_id', '=', 3];
                            $shengagentInfo = $UsersLevelAgentModel->where($wheresheng)->find();  //是否有存在省代理

                            $whereshi = [];
                            $whereshi[] = ['province', '=', $orderInfo['province']];
                            $whereshi[] = ['city', '=', $orderInfo['city']];
                            $whereshi[] = ['level_id', '=', 2];
                            $shiagentInfo = $UsersLevelAgentModel->where($whereshi)->find();  //是否有存在市代理

                            $wherequ = [];
                            $wherequ[] = ['province', '=', $orderInfo['province']];
                            $wherequ[] = ['city', '=', $orderInfo['city']];
                            $wherequ[] = ['district', '=', $orderInfo['district']];
                            $wherequ[] = ['level_id', '=', 1];
                            $qusagentInfo = $UsersLevelAgentModel->where($wherequ)->find();  //是否有存在区代理

                            $wherejiedao = [];
                            $wherejiedao[] = ['province', '=', $orderInfo['province']];
                            $wherejiedao[] = ['district', '=', $orderInfo['district']];
                            $wherejiedao[] = ['city', '=', $orderInfo['city']];
                            $wherejiedao[] = ['street', '=', $orderInfo['street']];
                            $wherejiedao[] = ['level_id', '=', 4];
                            $jiedaosagentInfo = $UsersLevelAgentModel->where($wherejiedao)->find();   //是否有存在街道代理

                            $shengMoneys = $shengagentInfo?$shengMoney:0;
                            $shiMoneys = $shiagentInfo?$shiMoney:0;
                            $quMoneys = $qusagentInfo?$quMoney:0;
                            $jiedaoMoneys = $jiedaosagentInfo?$jiedaoMoney:0;

                            if($shengMoney > 0 && $agentInfo['level_id'] == 3){
                                //如果有设置省奖励
                                $jichaMoney = abs($shengMoney-$shiMoneys-$quMoneys-$jiedaoMoneys);
                                $dividend_amount_region += $jichaMoney * $goods['goods_number'];
                            }else{
                                //如果有设置市奖励 并且有市代理
                                if($shiMoney > 0 && $agentInfo['level_id'] == 2){
                                    //判断市上面是否有省奖励用户
                                    if(!empty($shengagentInfo)){
                                        $dividend_amount_region += $shiMoney * $goods['goods_number'];
                                    }else{
                                        $jichaMoney = abs($shiMoney-$quMoneys-$jiedaoMoneys);
                                        $dividend_amount_region += $jichaMoney * $goods['goods_number'];
                                    }

                                }else{
                                    //如果有设置区奖励 并且有区代理
                                    if($quMoney > 0 && $agentInfo['level_id'] == 1){
                                        //判断区上面是否有市奖励用户


                                        if(!empty($shiagentInfo) || !empty($shengagentInfo)){
                                            $dividend_amount_region += $quMoney * $goods['goods_number'];
                                        }else{
                                            if(empty($shengagentInfo) && empty($shiagentInfo)){
                                                $jichaMoney = abs($quMoney-$jiedaoMoneys);
                                                $dividend_amount_region += $jichaMoney * $goods['goods_number'];

                                            }else{
                                                $dividend_amount_region += $quMoney * $goods['goods_number'];
                                            }

                                            //$jichaMoney = abs($quMoney-$jiedaoMoney);
                                            //$dividend_amount_region += $jichaMoney * $goods['goods_number'];
                                        }

                                    }else{
                                        //如果有设置街道奖励
                                        $dividend_amount_region += $num * $goods['goods_number'];
                                    }
                                }
                            }
                            //琳凯end 区域奖励级差奖励计算逻辑
                            //$dividend_amount_region += $num * $goods['goods_number'];
                        }
                    }

                    if ($dividend_amount_region > 0) {
                        $returnArr['dividend_amount'] += $dividend_amount_region;
                        $agentUser = $this->UsersModel->info($agentInfo['user_id']);
                        $res = $this->createLog($orderInfo, $agentUser, $dividend_amount_region, $level['level_name'] . '区域奖', '用户【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount_region . '元' . $level['level_name'] . '区域代理奖励', $dividend_goods_total, 'none');
                        if ($res !== true) return false;
                    }
                }
            }
        }

        if ($orderInfo['order_type'] == 4) { // 加盟区奖励
//            if(  $orderInfo['order_status']  <1){
//                return $returnArr;
//            }
            if($orderInfo['order_status'] <1){
                return $returnArr;
            }

            if ($parentId < 1) return $returnArr;//没有上级不执行
            $userInfo = $this->UsersModel->info($parentId); //获取会员信息  $parentId为上级用户ID
            $dividend_amount = 0;
            $see_dividend_amount = 0;
            $same_dividend_amount = 0;
            $sameUserId = 0;
            $profitUser = [];
            // 见点收益会员
            if ($userInfo['role_id'] == 2) {
                $sameUserId = $userInfo['pid'];
            } else {
                $profitUser = $this->UsersModel->info($userInfo['profit_pid']);
                if ($profitUser['role_id'] < 2) {
                    $profitUid = $profitUser['pid'];
                    do {
                        $profitUser = $this->UsersModel->info($profitUid);
                        $profitUid = $profitUser['pid'];
                        if ($profitUser['role_id'] == 2) break;
                    } while ($profitUid > 0);
                }

                $sameUserId = $profitUser['pid']; // 见点收益会员
            }
            // 平级奖用户
            $sameUser = [];
            if ($sameUserId > 0) {
                do {
                    $sameUser = $this->UsersModel->info($sameUserId);
                    $sameUserId = $sameUser['pid'];
                    if ($sameUser['role_id'] == 2) break;
                } while ($sameUserId > 0);
            }
            foreach ($dividend_goods as $k => $goods) {
                $boss_dividend_amount = 0; // 老板收益
                if ($goods['goods_type'] !== 4) {
                    continue;
                }

                if (empty($goods['award_value'][$userInfo['role_id']]) == false) { // 直推奖
                    $val = $goods['award_value'][$userInfo['role_id']];
                    if (empty($val['num']) == false && !is_array($val['num'])) {
                        $dividend_amount += $val['num'] * $goods['goods_number'];
                        $boss_dividend_amount = $val['num'] * $goods['goods_number'];
                    }
                };
                if ($userInfo['role_id'] < 2 && empty($profitUser) == false) { // 见点奖
                    $val = $goods['award_value'][$profitUser['role_id']];
                    if (empty($val['see_num']) == false) {
                        $boss_dividend_amount = $val['see_num'] * $goods['goods_number'];
                        $see_dividend_amount += $boss_dividend_amount;
                    }

                }

                if ($boss_dividend_amount > 0 && empty($sameUser) == false) { // 平级奖
                    $val = $goods['award_value'][$sameUser['role_id']];
                    if (empty($val['same_num']) == false) {
                        $same_dividend_amount += bcdiv($boss_dividend_amount * $val['same_num'], 100, 2);
                    }
                }
            }
//            $status = 'none';
            if ($dividend_amount > 0) {
                $returnArr['dividend_amount'] += $dividend_amount;
                $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$userInfo['user_id'].'_直推奖_'.$buyUserInfo['user_id']));
                $res = $this->createLog($orderInfo, $userInfo, $dividend_amount, '直推奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' .
                    $dividend_amount . '元直推奖励', $dividend_goods_total, $status,0,$md5Log);
                if ($res == false) return false;
            }

            if ($see_dividend_amount > 0) {
                $returnArr['dividend_amount'] += $see_dividend_amount;
                $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$profitUser['user_id'].'见点奖'.$buyUserInfo['user_id']));
                $res = $this->createLog($orderInfo, $profitUser, $see_dividend_amount, '见点奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $see_dividend_amount . '元见点奖励', $dividend_goods_total, $status,0,$md5Log);
                if ($res == false) return false;
            }
            if ($same_dividend_amount > 0) {
                $returnArr['dividend_amount'] += $same_dividend_amount;
                $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$userInfo['user_id'].'平级奖_'.$buyUserInfo['user_id']));
                $res = $this->createLog($orderInfo, $sameUser, $same_dividend_amount, '平级奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买加盟区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $same_dividend_amount . '元平级奖励', $dividend_goods_total, $status,0,$md5Log);
                if ($res == false) return false;
            }
        } else if ($orderInfo['order_type'] == 0 || $orderInfo['order_type'] == 6) {


            $dailicount = 0;
            $laobancount = 0;
            $vipcount = 0;
            $cuserInfo = $this->UsersModel->info($orderInfo['user_id']); //获取会员信息
//            $dailicount = $cuserInfo['role']['level'] == 4?1:0;

            do {
                $nowLevel++;
                $userInfo = $this->UsersModel->info($parentId); //获取会员信息

                $parentId = $userInfo['pid'];

                //琳凯start
                if($buyUserInfo['profit_pid'] == 0){
                    //$userInfo = $this->UsersModel->info($buyUserInfo['pid']); //获取会员信息  如果没有所属上级就直接用直接上级（推荐人）
                    //$parentId = $userInfo['pid'];
                }
                //琳凯end

                $dividend_amount = 0;
                $type = 'none';

                // 平级奖用户
                $sameUserId = $parentId;
                $same_dividend_amount = 0;
                $sameUser = [];
                if ($sameUserId > 0) {
                    do {
                        $sameUser = $this->UsersModel->info($sameUserId);
                        $sameUserId = $sameUser['pid'];
                        if ($sameUser['role_id'] == 2) break;
                    } while ($sameUserId > 0);
                }


                foreach ($dividend_goods as $goods) {
                    $award_value = $goods['award_value'];
                    $val = 0;
                    if($award_value){
                        foreach ($award_value as $awards){
                            if($awards['buyId'] == $cuserInfo['role_id']){
                                $val = $awards['daili'];

                            }
                        }
                    }else{
                        continue;
                    }

//                    if (empty($goods['award_value'][$userInfo['role_id']]['num'][1])) continue;
//                    $val = $goods['award_value'][$userInfo['role_id']]['num'][1];


                    if ($userInfo['role']['level'] == 3 && $vipcount == 0) {

//                        echo "会员积分" . $val . '<br>';
                        $dividend_amount = 0;
                        $type = 'vip';
                        $vipcount++;
                    } else if ($userInfo['role']['level'] == 4 && $dailicount == 0) {
//                        echo "代理" . $val . '<br>';
                        $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);


                        $dailicount++;
                    } else if ($userInfo['role']['level'] == 5 && $laobancount == 0) {
//                        $jc = 0;
//                        if ($dailicount > 0) {
//                            $jc = empty($goods['award_value'][1]['num'][1]) ? 0 : $goods['award_value'][1]['num'][1];
//                        }
//                        $val = $val - intval($jc);
                        $jc = 0;
                        if($award_value){
                            foreach ($award_value as $awards){
                                if($awards['buyId'] == $cuserInfo['role_id']){
                                    $jc = $awards['jingli'];
                                }
                            }
                        }
                        if ($dailicount > 0) {
                            $val =  ($jc)-$val;

                        }else{
                            if($award_value){
                                foreach ($award_value as $awards){
                                    if($awards['buyId'] == $cuserInfo['role_id']){
                                        $val = $awards['jingli'];
                                        $dailis = $awards['daili'];   //琳凯

                                    }
                                }
                            }
                        }
//                        var_dump('val:',$val);
//                        var_dump('jc:',$jc);exit;
//                        echo "老板" . $val . '<br>';

                        //琳凯start
                        $samesameUserObj = $this->UsersModel->info($orderInfo['user_id']);

                        $samesameUserId = $samesameUserObj['pid']; //上级用户id
                        $samesameInfo = $this->UsersModel->info($samesameUserId); //获取上级用户信息 $parentId 为上级用户ID  $samesameInfo上上级用户id,经理才有平级奖

                        //当前用户上上级用户信息
                        $samesamessUserId = $samesameInfo['pid'];
                        $samesamessInfo = $this->UsersModel->info($samesamessUserId);

                        //如果上级不为空
                        if($samesameInfo['role_id'] || !empty($samesameInfo['role_id'])){
                            //如果有上上级
                            if($samesamessInfo['role_id'] || !empty($samesamessInfo['role_id'])){
                                if($samesameInfo['role_id'] == 1 && $samesamessInfo['role_id'] == 2){
                                    $jicha = $val-$dailis;//琳凯
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                                }else if($samesameInfo['role_id'] == 1 && $samesamessInfo['role_id'] == 1){
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);
                                }else if($samesameInfo['role_id'] == 2 && $samesamessInfo['role_id'] == 2){
                                    $jicha = $val-$dailis;//琳凯
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                                }
                            }else{
                                $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);
                            }

                        }

                        //如果购买者的上级是代理 ，上上级是经理则 经理拿级差奖励
                        /*
                        if($samesamessInfo['role_id'] == 2){

                            //如果上级直接是经理 那么拿全部
                            if($samesameInfo['role_id'] == 2){
                                if($samesameUserObj['role_id'] == 1){
                                    $jicha = $val-$dailis;//琳凯
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                                }else{
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);
                                }
                            }else{
                                $jicha = $val-$dailis;//琳凯
                                $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                            }


                        }else{

                            //如果上级直接是经理 那么拿全部
                            if($samesameInfo['role_id'] == 2){
                                if($samesameUserObj['role_id'] == 1){
                                    $jicha = $val-$dailis;//琳凯
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                                }else{
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);
                                }
                            }else{
                                if($samesameInfo['role_id'] == 1 && $samesamessInfo['role_id'] == 1){
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($val) * $goods['goods_number'], 100, 2);
                                }else{
                                    $jicha = $val-$dailis;//琳凯
                                    $dividend_amount += bcdiv($goods['sale_price'] * ($jicha) * $goods['goods_number'], 100, 2);//琳凯
                                }

                            }
                        }
                        */


                        //琳凯end



                        $laobancount++;
                    }



                    if (empty($sameUser) == false) { // 平级奖
                        $same_dividend_amount += bcdiv($dividend_amount *10, 100, 2);
                    }

                }


                $counter_file = 'Yhknew20230804-1.txt';
                $fopen = fopen($counter_file,'a+');
                fputs($fopen,date('Y-m-d H:i:s',time()).' dividend_amount:'.$dividend_amount.'，samesamessInfo[role_id]：'.$samesamessInfo['role_id'].',samesameInfo[role_id]：'.$samesameInfo['role_id'].',计算签名：'.$samesameInfo['role_id'].'\r\n');
                fclose($fopen);


                if ($dividend_amount > 0) {
                    $returnArr['dividend_amount'] += $dividend_amount;
                    $md5Log = strtolower(md5($orderInfo['order_sn']."_".$parentId.'_'.$userInfo['user_id'].'分销奖_'.$buyUserInfo['user_id']));

                    $this->createLog($orderInfo,
                        $userInfo,
                        $dividend_amount,
                        '分销奖',
                        '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount . ($userInfo['role']['level'] == 1 ? '购物分' : '元'),
                        $dividend_goods_total,
                        $type,
                        0,
                        $md5Log
                    );
                }

                //平级奖励

                //琳凯start
                //$sameUser = $this->UsersModel->info($sameUserId);
                //$sameUserId = $sameUser['pid'];
                $samesameUserObj = $this->UsersModel->info($orderInfo['user_id']);
                $samesameUserId = $samesameUserObj['pid']; //上级用户id
                $samesameInfo = $this->UsersModel->info($samesameUserId); //获取上级用户信息 $parentId 为上级用户ID  $samesameInfo上上级用户id,经理才有平级奖

                //当前用户上上级用户信息
                $samesamessUserId = $samesameInfo['pid'];
                $samesamessInfo = $this->UsersModel->info($samesamessUserId);




                //if ($sameUser&&$same_dividend_amount > 0) {
                if ($sameUser && $same_dividend_amount > 0 && $samesameInfo['role_id'] == 2 && $samesamessInfo['role_id'] == 2) {
                    if($samesameUserObj['role_id'] == 2 && $samesameInfo['role_id'] == 2){

                    }else{
                        //琳凯end
                        $returnArr['dividend_amount'] += $same_dividend_amount;
                        $md5Log = strtolower(md5($orderInfo['order_sn'].'_'.$userInfo['user_id'].'平级奖_'.$buyUserInfo['user_id']));
                        $res = $this->createLog($orderInfo, $sameUser, $same_dividend_amount, '平级奖', '`下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $same_dividend_amount . '元平级奖励', $dividend_goods_total, $status,0,$md5Log);
                        //if ($res == false) return false;
                    }

                }
            } while ($parentId > 0 && $orderInfo['order_type'] == 6 && $orderInfo['membermoney'] > 0);
            do {
                /*
                $nowLevel++;
                $userInfo = $this->UsersModel->info($parentId); //获取会员信息

                $role = DividendRoleModel::where('role_id', $userInfo['role_id'])->field('role_id,level')->find();

                $parentId = $userInfo['pid'];
                $dividend_amount = 0;
                foreach ($dividend_goods as $goods) {

                    if (empty($goods['award_value'][$userInfo['role_id']])) continue;
                    $val = $goods['award_value'][$userInfo['role_id']]['num'];


                    if ($role['level'] == 1) {


                        //AccountModel::where('user_id',$parentId)->setInc('integral_money',$val[$nowLevel]);
                        $changedata['change_desc'] = '购物分返现';
                        $changedata['change_type'] = 3;
                        $changedata['integral_money'] = $val[$nowLevel];
                        $res = (new AccountModel())->change($changedata, $userInfo['user_id'], false);
                        $dividend_amount = $changedata['integral_money'];

                        //会员购物积分返现
                    } else {

                        $dividend_amount += bcdiv($goods['sale_price'] * $val[$nowLevel] * $goods['goods_number'], 100, 2);
                    }
                }
                if ($dividend_amount > 0) {
                    $returnArr['dividend_amount'] += $dividend_amount;
                    $res = $this->createLog($orderInfo, $userInfo, $dividend_amount, '分销奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买普通区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount . ($role['level'] == 1 ? '购物分' : '元') . $nowLevel . '级奖励', $dividend_goods_total, $status);
                }
                */

                $nowLevel++;
                $userInfo = $this->UsersModel->info($parentId); //获取会员信息

                $role = DividendRoleModel::where('role_id', $userInfo['role_id'])->field('role_id,level')->find();

                $parentId = $userInfo['pid'];

                $buypid = $buyUserInfo['pid'];
                $piduserInfo = $this->UsersModel->info($buypid); //获取上级会员信息



                $dividend_amount = 0;
                foreach ($dividend_goods as $goods) {

                    if ($goods['membermoney'] > 0 && $piduserInfo['role_id'] == 3 && $buyUserInfo['role_id'] == 3){

                        //AccountModel::where('user_id',$parentId)->setInc('integral_money',$val[$nowLevel]);
                        $changedata['change_desc'] = '购物分返现';
                        $changedata['change_type'] = 3;
                        $changedata['integral_money'] = $goods['membermoney']*$goods['goods_number'];

                        $dividend_amount = $goods['membermoney']*$goods['goods_number'];

                        $res = (new AccountModel())->change($changedata, $piduserInfo['user_id'], false);

                        //加到用户积分里
                        $useraccount = Db::table('users_account')->where('user_id',$piduserInfo['user_id'])->find();


                        $integral_money = sprintf("%01.2f",$useraccount['integral_money']+$dividend_amount);
                        $uparr['integral_money'] = $useraccount['integral_money'];

                        $useraccountres = Db::table('users_account')->where('user_id',$piduserInfo['user_id'])->update($uparr);

                        //会员购物积分返现

                    }

                }
                if ($dividend_amount > 0) {
                    $returnArr['dividend_amount'] += $dividend_amount;
                    $res = $this->createLog($orderInfo, $piduserInfo, $dividend_amount, '会员推荐会员购物分奖', '下级【' . $buyUserInfo['user_id'] . '-' . userInfo($buyUserInfo['user_id']) . '】购买会员区产品，订单编号【' . $orderInfo['order_sn'] . '】，获得' . $dividend_amount . ($role['level'] == 1 ? '购物分' : '购物分') . $nowLevel . '级奖励', $dividend_goods_total, $status);
                }
            } while ($parentId > 0);
        }

        return $returnArr;
    }



    /**
     * [createLog 保存分佣记录]
     * @param array $orderInfo [订单信息]
     * @param array $userInfo [用户信息]
     * @param float $dividend_amount [分佣金额]
     * @param string $award_name [分佣名]
     * @param string $level_award_name [分佣说明]
     * @param integer $status [分佣状态]
     * @param float $amount [参与分佣的金额]
     * @param integer $nowLevel [当前处理级别]
     * @return boolean                  [处理结果]
     */
    public function createLog($orderInfo = [], $userInfo = [], $dividend_amount = 0.00, $award_name = '', $level_award_name = '', $amount = 0.00, $status = 0, $nowLevel = 0,$md5log='')
    {
        $DividendInfo = settings('DividendInfo');
        $dividend_bean = 0;
        $type = 0;
        if (strstr($award_name, "区域")) {
            $type = 1;
        }
        $rebate_push_num = $this->UsersModel
            ->where([
                ['pid', '=', $userInfo['user_id']],
                ['role_id', '=', 2],
//                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        $AccountModels = new AccountModel();

        if ($DividendInfo['rebate_push_num'] > $rebate_push_num) {
            $total_dividend_amount = $dividend_amount;
            $dividend_amount = 0;
            $dividend_amount = $status == 'vip' ? $total_dividend_amount : bcdiv($total_dividend_amount * $DividendInfo['balance_rebate'], 100, 2);
            $dividend_bean = $status == 'vip' ? 0 : bcdiv($total_dividend_amount * $DividendInfo['integral_rebate'], 100, 2);
        }else{
            $AccountModels->releaseSupport($userInfo['user_id']);
        }
        $inArr['dividend_amount'] = $dividend_amount;
        $inArr['dividend_bean'] = $dividend_bean;
        $inArr['order_type'] = 'order';
        $inArr['status'] = 9;
        $inArr['order_id'] = $orderInfo['order_id'];
        $inArr['order_sn'] = $orderInfo['order_sn'];
        $inArr['buy_uid'] = $orderInfo['user_id'];
        $inArr['order_amount'] = $amount;
        $inArr['dividend_uid'] = $userInfo['user_id'];

        $inArr['role_id'] = $userInfo['role_id'];
        $inArr['role_name'] = $userInfo['role']['role_name'];
        $inArr['level'] = $nowLevel;
        $inArr['award_id'] = 1;
        $inArr['type'] = $type;
        $inArr['award_name'] = $award_name;
        $inArr['level_award_name'] = $level_award_name;
        $inArr['add_time'] = $inArr['update_time'] = time();
        if($this->Model->where(['award_name'=>$award_name,'order_sn'=>$inArr['order_sn'],'dividend_uid'=>$inArr['dividend_uid']])->find()){
            return  false;
        }

        $res = $this->Model->insert($inArr);

        if (!$res) return false;
        $AccountModel = new AccountModel();
        $changedata['change_desc'] = $inArr['level_award_name'];
        $changedata['change_type'] = 4;
        $changedata['by_id'] = $inArr['order_id'];
        $changedata['from_uid'] = $inArr['user_id'];
        $changedata[$status == 'vip' ? 'integral_money' : 'balance_money'] = $inArr['dividend_amount'];
        $changedata['bean_value'] = $inArr['dividend_bean'];
        $changedata['total_dividend'] = ($inArr['dividend_amount'] + $inArr['dividend_bean']);
        $changedata['md5log'] = $md5log;
        $AccountModel->change($changedata, $inArr['dividend_uid'], false);
        return true;
    }
    /*------------------------------------------------------ */
    //-- 执行升级方案
    //-- $orderInfo array 订单信息
    //-- $isup bool 是否更新会员信息
    /*------------------------------------------------------ */
    public function evalLevelUp(&$orderInfo)
    {
        //执行分销身份升级处理
        $roleList = (new DividendRoleModel)->getRows();
        $LogSysModel = new \app\member\model\LogSysModel();
        // $oldFun = '';
        // $DividendInfo = settings('DividendInfo');
        // $_roleList = array_merge([['role_name' => '粉丝', 'role_id' => 0, 'level' => 0]], $roleList);
        // $UsersBindSuperiorModel = new \app\member\model\UsersBindSuperiorModel();
        $user_id = $orderInfo['user_id'];
        // $goodsList = (new OrderGoodsModel)->where('order_id', $orderInfo['order_id'])->select();
        $userLevel = (new \app\member\model\UsersLevelApplyModel)->getRows();
        do {
            unset($stats);
            $userInfo = $this->UsersModel->info($user_id);//获取会员信息
            $userRoleLevel = 0;
            if ($userInfo['role_id'] > 0) {
                $role = DividendRoleModel::where('role_id', $userInfo['role_id'])->field('role_id,level')->find();// $roleList[$userInfo['role_id']]['level'];//获取当前会员身份等级
                if (!empty($role)) {
                    $userRoleLevel = $role['level'];
                }
            }
            $stats['subRoleCount'] = [];
            //汇总直推身份的代理数
            $where = [];
            $where[] = ['pid', '=', $user_id];
            $where[] = ['role_id', '=', 1];
            $stats['subRoleCount'] = $this->UsersModel->where($where)->count();
            $upRole = [];
            foreach ($roleList as $role) {
                if ($role['level'] <= $userRoleLevel) {//当前分销身份低于等于用户现身份，跳过
                    continue;
                };

                if ($role['is_auto'] == 9) {//手动调整,跳过
                    continue;
                }
                $upLeveValue = $role['upleve_value'];
                //购买会员额外处理
                if ($user_id == $orderInfo['user_id']) {
                    //购买身份商品直接升级


                    if ($orderInfo['order_type'] == 4) {
                        if ($role['role_id'] == 1) {
                            $upRole = $role;
                            break;
                        };
                    }
                    //购买会员商品直接升级会员
                    if ($orderInfo['order_type'] == 6) {
                        if ($role['role_id'] == 3) {
                            $upRole = $role;
                            break;
                        };
                    }
                }
                if ($userInfo['role_id'] == 0) continue;
                //购买会员额外处理end

                if ($upLeveValue['referral'] > 0) {

                    if ($stats['subRoleCount'] >= $upLeveValue['referral']) $upRole = $role;
                }
            }

            if (empty($upRole) == false) {
                $upData = [];
                $upData['last_up_role_time'] = time();
                $upData['role_id'] = $upRole['role_id'];

                if ($upData['role_id'] == 1) {
                    $upData['up_agent_time'] = time();
                }

                $res = $this->UsersModel->upInfo($user_id, $upData);
                if ($res < 1) {
                    return false;
                }
                $inData['edit_id'] = $user_id;
                $inData['log_info'] = '【' . ($userInfo['role_id'] == 0 ? '粉丝' : $roleList[$userInfo['role_id']]['role_name']) . '】升级为【' . $upRole['role_name'] . '】';
                $inData['module'] = request()->path();
                $inData['log_ip'] = request()->ip();
                $inData['log_time'] = time();
                $inData['user_id'] = 0;
                $LogSysModel->create($inData);

                // 更换收益上级
                if ($upData['role_id'] == 2) {
                    $upUsers = $this->UsersModel
                        ->where('pid', $user_id)
                        ->limit(2)
                        ->order('up_agent_time Desc')
                        ->field('profit_pid,user_id')
                        ->select()
                        ->toArray();
                    $parentBossId = $userInfo['profit_pid'];
                    $bossId = 0;
                    do {
                        $ubossInfo = $this->UsersModel->field('role_id,user_id,profit_pid')->find($parentBossId);
                        if (empty($ubossInfo)) {
                            $parentBossId = 0;
                            break;
                        }
                        $parentBossId = $ubossInfo->profit_pid;
                        if ($ubossInfo['role_id'] == 2) {
                            $bossId = $ubossInfo->user_id;
                            break;
                        }

                    } while ($parentBossId > 0);
                    foreach ($upUsers as $us) {
                        if ($us['profit_pid'] != $bossId) {
                            $res = $this->UsersModel->where('user_id', $us['user_id'])->update(['profit_pid' => $bossId]);
                            if (!$res) {
                                return false;
                            }
                        }
                    }
                }
                unset($upData);
                unset($inData);
            }
            $upLevel = [];
            foreach ($userLevel as $Level) {
                if ($Level['level_id'] <= $userInfo['level_id'] || $Level['push_num'] <= 0) continue;
                if ($stats['subRoleCount'] < $Level['push_num']) continue;
                $upLevel = $Level;
            }
            if (empty($upLevel) == false) {
                $upData = [];
                $upData['level_id'] = $upLevel['level_id'];
                $res = $this->UsersModel->upInfo($user_id, $upData);
                if ($res < 1) {
                    return false;
                }
                $inData = [];
                $inData['edit_id'] = $user_id;
                $inData['log_info'] = '达到升级条件升级为' . $upLevel['level_name'];
                $inData['module'] = request()->path();
                $inData['log_ip'] = request()->ip();
                $inData['log_time'] = time();
                $inData['user_id'] = 0;
                $LogSysModel->create($inData);
                unset($inData);
            }

            $user_id = $userInfo['pid'];//继续处理上级id
        } while ($user_id > 0);
        //


        return true;
    }

}
